package com.headwind.mq.rabbitmq;

import com.google.gson.Gson;
import com.headwind.mq.Constance;
import com.headwind.mq.rabbitmq.message.MyMessage;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author : Headwind
 * @version : 1.0
 * @date : Created in 2020/8/10
 * @description : 监听消息队列
 */
@Component
@Log4j2
public class ReceiverMessage {

    @RabbitHandler
    @RabbitListener(queues = Constance.MESSAGE_QUEUE_X)
    public void messageListener(MyMessage myMessage, Message message, Channel channel) {
        // 如果手动ACK,消息会被监听消费,但是消息在队列中依旧存在,如果未配置 acknowledge-mode 默认是会在消费完毕后自动ACK掉
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("队列，手动ACK，接收消息：{}", new Gson().toJson(myMessage));
            // 通知 MQ 消息已被成功消费,可以ACK了
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            try {
                // 处理失败,重新压入MQ
                channel.basicRecover();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
